/**
 * router/index.ts
 *
 * Automatic routes for `./src/pages/*.vue`
 */

// Composables
import {createRouter, createWebHistory} from 'vue-router/auto'
import {useMenuStore} from "@/stores/menu";
import pinia from '../stores'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import {CacheManager} from "@/cache";
import GlobalConstants from "@/constants/GlobalConstants";
import {RouteLocationNormalized, Router} from "vue-router";

const menuStore = useMenuStore(pinia);

const router: Router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: menuStore.initStaticMenus(),
})

// Workaround for https://github.com/vitejs/vite/issues/11804
router.onError((err: any, to: RouteLocationNormalized) => {
  if (err?.message?.includes?.('Failed to fetch dynamically imported module')) {
    if (!localStorage.getItem('vuetify:dynamic-reload')) {
      console.log('Reloading page to fix dynamic import error')
      localStorage.setItem('vuetify:dynamic-reload', 'true')
      location.assign(to.fullPath)
    } else {
      console.error('Dynamic import error, reloading page did not fix it', err)
    }
  } else {
    console.error(err)
  }
})

router.isReady().then(() => {
  localStorage.removeItem('vuetify:dynamic-reload')
})

router.beforeEach(async (to: RouteLocationNormalized) => {
  NProgress.start()
  //当前访问路径实际匹配的路由路径
  const path = to.path
  if (CacheManager.getToken()) {
    if (!menuStore.loadingComplete) {
      await menuStore.initDynamicMenus()
      if (path === GlobalConstants.LOGIN_PATH) {
        //token存在，不允许访问登录或注册页面
        return {path: GlobalConstants.DEFAULT_PATH}
      } else {
        return {path: to.path, query: to.query}
      }
    } else {
      if (path === GlobalConstants.LOGIN_PATH) {
        //token存在，不允许访问登录或注册页面
        return {path: GlobalConstants.DEFAULT_PATH}
      }
    }
  } else {
    //token不存在，只能进入允许匿名访问的页面
    if (GlobalConstants.ANONYMOUS_ACCESS_PATH.indexOf(path) === -1) {
      return {path: GlobalConstants.LOGIN_PATH}
    }
  }
})
router.afterEach((to: RouteLocationNormalized) => {
  menuStore.pushHistory(to)
  NProgress.done()
})

export default router
